import asyncio
from qasync import QEventLoop, asyncSlot
from MyTT import EMA
import numpy as np
import pandas as pd
from tqsdk import TqApi
from db_manager import connect_db, get_monitored_products
import time
from threading import Thread
from tqsdk import TqApi, TqAuth, TqAccount, TqSim,TqKq

@asyncSlot()
async def async_start():
    """启动策略"""
    tq_kq = TqKq()
    api = TqApi(account=tq_kq, auth=TqAuth("cps168", "alibaba999"))
    lots = 1  # 每笔交易的手数
   
    
    # 从数据库获取监控品种
    conn = connect_db()
    monitored_products = get_monitored_products(conn)
    conn.close()
    
    # 为每个品种启动处理线程
    for symbol in monitored_products:
        Thread(target=lambda: asyncio.run(_process_product(api,symbol))).start()

@asyncSlot()
async def _process_product(api,symbol):
    api = api
    """单个品种处理协程"""
    print(f"开始处理品种: {symbol}")  # 添加日志
    try:
        klines = api.get_kline_serial(symbol, 300, 500)        
        while True:
            deadline = time.time() + 1
            api.wait_update(deadline=deadline)         
            print(f"{symbol} 正在运行...", flush=True)  # 添加flush确保及时输出
            if api.is_changing(klines.iloc[-1], "datetime"):
                if not klines.close.iloc[-1]:
                    print("K线已变化")
                    q = (3*klines.close + klines.low + klines.open + klines.high) / 6
                    ma_values = _calculate_ma(q)
                    short_ma = ma_values['ma']
                    ema_7 = ma_values['ema']
                    
                    position = api.get_position(symbol)
                    
                    # 平空仓逻辑
                    if short_ma[-2] > ema_7[-2]:  
                        if position.pos_short > 0:
                            api.insert_order(symbol, direction="BUY", offset="CLOSE", 
                                            volume=position.pos_short)
                    # 开多仓逻辑
                    if position.pos_long == 0 and position.pos_short == 0 and short_ma[-3] < ema_7[-3] and short_ma[-2] > ema_7[-2]:
                        api.insert_order(symbol, direction="BUY", offset="OPEN", 
                                        volume=lots)
                        
                    # 平多仓逻辑
                    if short_ma[-2] < ema_7[-2]:  
                        if position.pos_long > 0:
                            api.insert_order(symbol, direction="SELL", offset="CLOSE", 
                                            volume=position.pos_long)
                    # 开空仓逻辑
                    if position.pos_long == 0 and position.pos_short == 0 and short_ma[-3] > ema_7[-3] and short_ma[-2] < ema_7[-2]:
                        api.insert_order(symbol, direction="SELL", offset="OPEN", 
                                        volume=lots)

    except Exception as e:
        print(f"处理品种 {symbol} 时出错: {e}")
    finally:
        print(f"结束处理品种: {symbol}")  # 添加日志


def _calculate_ma(q):
    """自定义权重计算（与原版完全一致）"""
    weights = np.arange(26, 0, -1)
    ma = []
    q_array = np.array(q)
    for i in range(len(q_array)):
        if i < 26:
            ma.append(np.nan)
            continue
        window = q_array[i-26:i+1]
        ma.append(np.dot(window, weights) / 351)
    
    ema_7 = EMA(pd.Series(ma), 7)
    return {'ma': ma, 'ema': ema_7.tolist()}

if __name__ == "__main__":
    pass
